<script lang="ts" setup>
import type { ShopGoodsApi } from '#/api/shop/goods';

import { computed, ref, nextTick } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';
import type { HandCardConsumptionApi } from '#/api/spa/handcard/asset';
import { calculateGoodsPurchase, submitGoodsPurchase } from '#/api/spa/handcard/asset';
import { $t } from '#/locales';
import ConsumptionDetailsGrid from './consumption-details-grid.vue'
import GoodsGrid from './goods-grid.vue'
import CartGrid from './cart-grid.vue'

interface CartItem extends ShopGoodsApi.Goods {
  quantity: number;
}

const emit = defineEmits<{
  success: [];
}>();

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    // 使用自定义按钮提交，默认确认不触发
    return;
  },
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      // 获取手牌信息
      const data = modalApi.getData();
      if (data?.handCardInfo) {
        handCardInfo.value = data.handCardInfo;
      }
      init();
      await nextTick();
      detailsGridRef.value?.gridApi?.query?.();
    }
  },
});

// 手牌信息
const handCardInfo = ref<any>(null);

// 计算弹窗标题
const modalTitle = computed(() => {
  if (handCardInfo.value) {
    const cardNumber =
      handCardInfo.value.cardNumber || handCardInfo.value.id || '未知';
    return `${$t('spa.handCard.consume')} - ${$t('spa.handCard.handCardNumber')}: ${cardNumber}`;
  }
  return $t('spa.handCard.consume');
});

// 商品检索与分页交由 GoodsGrid 管理

// 购物车相关
const cartList = ref<CartItem[]>([]);

// 商品/购物车列（vxe 版本已直接内联在模板中）

// 计算总金额
const totalAmount = computed(() => {
  return cartList.value.reduce((total, item) => {
    return total + (item.goodsSku?.price || 0) * item.quantity;
  }, 0);
});

// 汇总信息（由明细组件回传）
const consumptionSummary = ref<HandCardConsumptionApi.ConsumptionDetailsResponse | null>(null);
const detailsGridRef = ref<any>(null);
const cartGridRef = ref<any>(null);
const submitting = ref(false);
function onSummary(s: HandCardConsumptionApi.ConsumptionDetailsResponse | null) {
  consumptionSummary.value = s;
}

//

// 添加到购物车
function handleAddToCart(goods: ShopGoodsApi.Goods) {
  const existingItem = cartList.value.find(
    (item) => item.goods_id === goods.goods_id,
  );

  if (existingItem) {
    if (existingItem.quantity >= (goods.stock || 0)) {
      message.warning('库存不足');
      return;
    }
    existingItem.quantity += 1;
  } else {
    cartList.value.push({
      ...goods,
      quantity: 1,
    });
  }

  // 同步子组件内部数据源，确保立即可见
  cartGridRef.value?.addItem?.(goods);
  message.success('已添加到购物车');
}

// 从购物车移除
function handleRemoveFromCart(goodsId: number) {
  const index = cartList.value.findIndex((item) => item.goods_id === goodsId);
  if (index !== -1) {
    cartList.value.splice(index, 1);
  }
}

// 修改数量
function handleQuantityChange(item: CartItem) {
  if (item.quantity <= 0) {
    item.quantity = 1;
  }
  if (item.quantity > (item.stock || 0)) {
    item.quantity = item.stock || 0;
    message.warning('数量不能超过库存');
  }
}

// 清空购物车
function handleClearCart() {
  cartList.value = [];
}

// 提交消费
async function handleSubmit() {
  if (cartList.value.length === 0) {
    message.warning('请选择要消费的商品');
    return false;
  }

  // TODO: 调用后端消费购买接口（待提供）

  message.success('消费成功');
  emit('success');
  await modalApi.close();
  return true;
}

//

// 初始化（当前无逻辑）
function init() {}

// 将购物车映射为 goodsItems
function mapCartToGoodsItems() {
  return cartList.value.map((it) => ({
    goodsId: it.goods_id,
    goodsName: it.goods_name,
    goodsType: it.goods_type || 'goods',
    quantity: it.quantity,
    unitPrice: Number(it.goodsSku?.price || 0),
    discountAmount: 0,
    subtotalAmount: Number((it.goodsSku?.price || 0) * it.quantity),
    specification: it.goodsSku?.spec_name || '',
    unit: it.goodsSku?.unit || '',
    description: it.sub_title || '',
    remark: '',
  }));
}

async function onCalculate() {
  if (!handCardInfo.value?.id) {
    message.warning('缺少手牌ID');
    return;
  }
  const payload = {
    billId: consumptionSummary.value?.consumptionBill?.id,
    cardId: handCardInfo.value.id,
    operatorId: 1,
    remark: '计算商品购买金额',
    goodsItems: mapCartToGoodsItems(),
  } as any;
  const res = await calculateGoodsPurchase(payload);
  message.success(`试算成功：¥${Number(res?.totalAmount || 0).toFixed(2)}`);
}

async function onSubmit() {
  if (submitting.value) {
    return;
  }
  if (!handCardInfo.value?.id) {
    message.warning('缺少手牌ID');
    return;
  }
  if (!cartList.value.length) {
    message.warning('购物车为空');
    return;
  }
  const payload = {
    billId: consumptionSummary.value?.consumptionBill?.id,
    cardId: handCardInfo.value.id,
    operatorId: 1,
    remark: '提交商品购买',
    goodsItems: mapCartToGoodsItems(),
  } as any;
  try {
    submitting.value = true;
    const res = await submitGoodsPurchase(payload);
    message.success(`提交成功：成功条数 ${res?.successCount ?? 0}，总金额 ¥${Number(res?.totalAmount || 0).toFixed(2)}`);
    // 清空购物车
    cartList.value = [];
    cartGridRef.value?.clear?.();
    // 刷新明细
    await detailsGridRef.value?.gridApi?.query?.();
  } finally {
    submitting.value = false;
  }
}
</script>

<template>
  <Modal
    :title="modalTitle"
    :min-height="600"
    class="w-3/4"
    :style="{ top: '20px' }"
  >
    <div class="consume-modal-tabs">
      <a-tabs type="line" animated>
        <a-tab-pane key="buy" tab="购买 / 购物车">
          <div class="pane-buy">
            <div class="goods-section">
              <div class="section-header">
                <h3>{{ $t('spa.handCard.goodsList') }}</h3>
              </div>
              <GoodsGrid @add="handleAddToCart" />
            </div>
            <div class="cart-section">
              <div class="section-header">
                <h3>{{ $t('spa.handCard.shoppingCart') }}</h3>
                <a-popconfirm :title="$t('spa.handCard.clearCart') + '?'" @confirm="handleClearCart">
                  <a-button type="link" danger>
                    {{ $t('spa.handCard.clearCart') }}
                  </a-button>
                </a-popconfirm>
              </div>
              <div class="cart-grid-wrap">
                <CartGrid ref="cartGridRef" :items="cartList" @update:items="(list:any)=> (cartList.value = list)" @remove="handleRemoveFromCart" @total="(t:number)=>{}" />
              </div>
              <div class="cart-summary">
                <div class="total-info">
                  <span class="total-label">{{ $t('spa.handCard.totalAmount') }}:</span>
                  <span class="total-amount">¥{{ totalAmount.toFixed(2) }}</span>
                </div>
                <div class="action-buttons">
                  <a-space>
                    <a-button @click="onCalculate" :disabled="cartList.length===0">试算金额</a-button>
                    <a-button type="primary" @click="onSubmit" :disabled="cartList.length===0">提交购买</a-button>
                  </a-space>
                </div>
              </div>
            </div>
          </div>
        </a-tab-pane>
        <a-tab-pane key="consumption" tab="消费明细">
          <div class="pane-consumption">
            <ConsumptionDetailsGrid ref="detailsGridRef" :card-id="handCardInfo?.id" @summary="onSummary" />
            <div class="consumption-summary" v-if="consumptionSummary">
              <a-descriptions size="small" :column="2" bordered>
                <a-descriptions-item label="状态">{{ consumptionSummary.status }}</a-descriptions-item>
                <a-descriptions-item label="消费时长(分钟)">{{ consumptionSummary.durationMinutes }}</a-descriptions-item>
                <a-descriptions-item label="总消费">¥{{ Number(consumptionSummary.totalAmount || 0).toFixed(2) }}</a-descriptions-item>
                <a-descriptions-item label="已支付">¥{{ Number(consumptionSummary.paidAmount || 0).toFixed(2) }}</a-descriptions-item>
                <a-descriptions-item label="应付">¥{{ Number(consumptionSummary.payableAmount || 0).toFixed(2) }}</a-descriptions-item>
                <a-descriptions-item label="优惠">¥{{ Number(consumptionSummary.discountAmount || 0).toFixed(2) }}</a-descriptions-item>
              </a-descriptions>
            </div>
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>
    <template #footer>
      <a-space>
        <a-button @click="modalApi.close()">关闭</a-button>
      </a-space>
    </template>
  </Modal>
</template>

<style lang="less" scoped>
.consume-modal-tabs {
  .ant-tabs {
    .ant-tabs-content-holder {
      min-height: 560px;
    }
  }

  .pane-buy {
    display: grid;
    grid-template-columns: 1.1fr 0.9fr;
    gap: 16px;

    .goods-section,
    .cart-section {
      border: 1px solid #f0f0f0;
      border-radius: 6px;
      padding: 16px;
      background: #fff;
    }

    .goods-section {
      .section-header {
        margin-bottom: 12px;
        h3 {
          margin: 0;
          font-size: 16px;
          font-weight: 500;
        }
      }
    }

    .cart-section {
      .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;
        h3 {
          margin: 0;
          font-size: 16px;
          font-weight: 500;
        }
        .ant-btn-link {
          padding: 0;
          height: auto;
        }
      }

      .cart-grid-wrap {
        min-height: 260px;
      }

      .cart-summary {
        margin-top: 12px;
        padding-top: 12px;
        border-top: 1px solid #f0f0f0;
        .total-info {
          display: flex;
          justify-content: space-between;
          align-items: center;
          .total-label {
            font-size: 14px;
          }
          .total-amount {
            font-size: 18px;
            font-weight: 600;
            color: #ff4d4f;
          }
        }
      }
    }
  }

  .pane-consumption {
    border: 1px solid #f0f0f0;
    border-radius: 6px;
    padding: 16px;
    background: #fff;

    .consumption-summary {
      margin-top: 12px;
    }
  }
}
</style>
